// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Diagnostics;

namespace SnapObjects.Commons
{
    [DebuggerStepThrough]
    public sealed class LazyReference<T>
    {
        private Func<T> _initializer;
        private T _value;

        public LazyReference(Func<T> initializer)
        {
            _initializer = initializer;
        }

        public LazyReference(T value)
        {
            _value = value;
        }

        public T Value
        {
            get
            {
                if (_initializer != null)
                {
                    _value = _initializer();
                    _initializer = null;
                }

                return _value;
            }

            set
            {
                _value = value;
                _initializer = null;
            }
        }

        public bool HasValue => _initializer == null;

        public void Reset(Func<T> initializer)
        {
            _initializer = initializer;
            _value = default;
        }
    }
}
